/*
 * @(#)MaintDmsPaperDocumentAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;

/**
  MaintDmsPaperDocumentAction.java

  This class is for maint dms paper document.

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   14/10/2004
    @version         $Revision: 1.13.2.1 $
*/

public class MaintDmsPaperDocumentAction extends MaintDmsCompoundDocumentAction {

  public static final String REVISION = "$Revision: 1.13.2.1 $";

    
  public MaintDmsPaperDocumentAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PAPER_DOCUMENT);
  }
  
  /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
	  /*
	   * joan.xiong add code for bug EIP-172 by 2006/10/12
	   */
	  if(!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY))){
			  //&& request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY).equals("dms.message.records_rename")){
		  this.addMessage(request, (String)request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY));
		  request.getSession().removeAttribute(org.apache.struts.Globals.MESSAGE_KEY);
	  }
	  if(!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY))){
		  this.addError(request, (String)request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY));
		  request.getSession().removeAttribute(org.apache.struts.Globals.ERROR_KEY);
	  }
	  /*
	   * joan.xiong add code end
	   */
	  MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;
    // Set function code if necessary.
    if (!Utility.isEmpty(actionForm.getCurFunctionCode())) {
      this.setFunctionCode(actionForm.getCurFunctionCode());
    }

    String opMode = actionForm.getOpMode();
    String navMode = actionForm.getNavMode();
   
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager=sessionContainer.getPermissionManager();

    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    // Retrieve the default document profile settings.
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    docRetrievalManager.checkNSetDefaultProfileList(request);

    // Get the location path.
    parentID = actionForm.getParentID();
    rootID = actionForm.getRootID();
    docType = actionForm.getDocumentType();

    if (!GlobalConstant.NAV_MODE_VIEW.equals(navMode)){
       selectChildList(TextUtility.parseIntegerObj(actionForm.getID()), TextUtility.parseIntegerObj(actionForm.getRootID()), request,form);
    /* Retrieval the document information for display in JSP */


    // Retrieve the accessible public root list.
    List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
    request.setAttribute("publicRootList", publicRootList);
       
    // Retrieve the root folder document object.
    DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(actionForm.getRootID()));
    //Check for null parentID rootID hanling
    if ((Utility.isEmpty(parentID) || "null".equals(parentID) ||
        Utility.isEmpty(rootID) || "null".equals(rootID))  && permissionManager.getPersonalPermission().indexOf('I') > -1) {
      DmsRoot personalRoot = rootRetrievalManager.getRootObjectByOwnerID(sessionContainer.getUserRecordID());
      documentRoot = docRetrievalManager.getRootFolderByRootID(personalRoot.getID());
      parentID = TextUtility.formatIntegerObj(documentRoot.getParentID());
      rootID = TextUtility.formatIntegerObj(personalRoot.getID());
      actionForm.setRootID(rootID);
      actionForm.setParentID(parentID);
    } else if ((Utility.isEmpty(parentID) || "null".equals(parentID) || Utility.isEmpty(rootID) || "null".equals(rootID)) && !Utility.isEmpty(publicRootList)) {
    	DmsRoot publicRoot = (DmsRoot)publicRootList.get(0);
    	documentRoot = docRetrievalManager.getRootFolderByRootID(publicRoot.getID());
      parentID = TextUtility.formatIntegerObj(documentRoot.getID());
      rootID = TextUtility.formatIntegerObj(publicRoot.getID());
      actionForm.setRootID(rootID);
      actionForm.setParentID(parentID);
    }
    request.setAttribute("rootFolder", documentRoot);

    String path = "";
    if (parentID != null) {
      path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
    }
    request.setAttribute("location", path);

    // Retrieve the folder list for folder tree listing.
    List folderTreeList = docRetrievalManager.getFolderByParentIDRootID(documentRoot.getID(), new Integer(actionForm.getRootID()));
    request.setAttribute("folderTreeList", folderTreeList);
    /* END of JSP Retrieval */
    }
    
    if (GlobalConstant.OP_MODE_INSERT.equals(opMode)){
      // Insert operation.
      log.debug("enter insert Paper Document");
      try {
        this.insertRecord(mapping, actionForm, request, response);
        try {
          this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);
        } catch (ApplicationException e) {
          log.error(e, e);
          throw e;
        }
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_INSERT);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
//        actionForm.setNavMode(GlobalConstant.NAV_MODE_REFRESH);
      	actionForm.setNavMode(null);
      	actionForm.setOpMode(null);
        this.refreshFormData(mapping, actionForm, request, response);
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      } else {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
      }
      
    }else if(GlobalConstant.OP_MODE_UPDATE.equals(opMode)){
      log.debug("enter update Paper Document");
      try {
        this.updateRecord(mapping, actionForm, request, response);
        try {
          this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);
        } catch (ApplicationException e) {
          log.error(e, e);
          throw e;
        }
      this.commit(request);
      addMessage(request, MESSAGE_RECORD_INSERT);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
      	actionForm.setNavMode(null);
      	actionForm.setOpMode(null);
//        actionForm.setNavMode(GlobalConstant.NAV_MODE_REFRESH);
        this.refreshFormData(mapping, actionForm, request, response);
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      } else {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
      }
    }else{
      return super.execute(mapping,form,request,response);   
    }
  }
  
  /**
   *  Method updateRecord() - rewrite the parent function.             
   *
   *  @param      mapping                   ActionMapping from struts
   *  @param      form                      ActionForm from struts
   *  @param      request                   HttpServletReuqest
   *  @param      respond                   HttpServletRespond
   *  @throws     ApplicationException      Throws ApplicationException
   */
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {   
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);   
    MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;  
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    
    //Check duplicate reference number
    if(DmsDocument.PAPER_DOC_TYPE.equals(actionForm.getDocumentType())){   
      if (!Utility.isEmpty(actionForm.getReferenceNo())) {
        DmsDocument existsDocument = (DmsDocument)dmsDocumentDAO.getObjectByReferenceNo(actionForm.getReferenceNo());
        if ((existsDocument != null) && (new Integer(actionForm.getID()).intValue()!=existsDocument.getID().intValue())){
           throw new ApplicationException(DmsErrorConstant.DUPLICATE_REFERENCE_NO, null, actionForm.getReferenceNo());
        }
      }
     }
    
    super.updateRecord(mapping,form,request,response);
    dmsDocumentDAO=null;
  }
 
  
}